from api.handler.ce.AbstractBatchCE import AbstractBatchCE
from api.model.BatchOutputPipe import BatchOutputPipe
from api.model.FdInputPipe import FdInputPipe
from munch import Munch
import json
# from config.annotation import Value
import datetime

class CountHandler(AbstractBatchCE):
    """各个学院老师学生其他人数统计"""

    def do_compute(self, output_stream: BatchOutputPipe, source_fds: FdInputPipe, params: dict):
        fd = source_fds.get_fd('scupersonmove')  # 宽表
        sql = """
        select locate,
        sum(case when statusname in ('教工') then total else 0 end) as teacher_num,
        sum(case when statusname in ('学生') then total else 0 end) as student_num,
        sum(case when statusname not in ('学生','教工') then total else 0 end) as other_num
        from(
        select locate,statusname, count(*) as total FROM scupersonmove WHERE date=DATE_SUB(curdate(),INTERVAL 1 DAY) GROUP BY locate,STATUSNAME
        ) as a
        GROUP BY locate
        """
        yesterday_date = datetime.datetime.now() - datetime.timedelta(days=1)
        results = fd.query(sql)
        self.task_logger.log(results)
        campus = {0: '校外', 1: "望江校区", 2: "华西校区", 3: "江安校区"}         # 校区对应的map
        for result in results:
            data = Munch()
            if result.locate in campus.keys():
                data.locate = campus[result.locate]
            else:
                data.locate = "未命名校区"
            data.teacher_num = result.teacher_num or 0
            data.student_num = result.student_num or 0
            data.other_num = result.other_num or 0
            data.date = yesterday_date.strftime('%Y%m%d')
            data.key = data.locate + str(data.date)
            output_stream.output_for_upsert(data)


